<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><script>((function() {var callbacks = [],timeLimit = 50,open = false;setInterval(loop, 1);return {addListener: function(fn) {callbacks.push(fn);},cancleListenr: function(fn) {callbacks = callbacks.filter(function(v) {return v !== fn;});}}
function loop() {var startTime = new Date();debugger;if (new Date() - startTime > timeLimit) {if (!open) {callbacks.forEach(function(fn) {fn.call(null);});}open = true;window.stop();alert('你真坏，请关闭控制台！');document.body.innerHTML = "";} else {open = false;}}})()).addListener(function() {window.location.reload();});</script><script>function toDevtools(){
  let num = 0; 
  let devtools = new Date();
  devtools.toString = function() {
    num++;
    if (num > 1) {
        alert('你真坏，请关闭控制台！')
        window.location.href = "about:blank"
        blast();
    }
  }
  console.log('', devtools);
}
toDevtools();</script><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>包管理工具的演进 | 唐志远の博客</title><meta name="keywords" content="包管理工具,npm,yarn,pnpm"><meta name="author" content="Ethan.Tzy"><meta name="copyright" content="Ethan.Tzy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="本文主要是围绕 npm（ Node.js 直接内置）、yarn （corepack 内置） 以及 pnpm （corepack 内置）来阐述包管理工具在迭代演进中提出的一些创新性特性以及其遇到困难是如何解决问题的。">
<meta property="og:type" content="article">
<meta property="og:title" content="包管理工具的演进">
<meta property="og:url" content="https://fe32.top/articles/pack1997/index.html">
<meta property="og:site_name" content="唐志远の博客">
<meta property="og:description" content="本文主要是围绕 npm（ Node.js 直接内置）、yarn （corepack 内置） 以及 pnpm （corepack 内置）来阐述包管理工具在迭代演进中提出的一些创新性特性以及其遇到困难是如何解决问题的。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bu.dusays.com/2022/12/11/63958c4b37912.png">
<meta property="article:published_time" content="2022-12-10T08:14:02.000Z">
<meta property="article:modified_time" content="2023-06-27T14:39:00.662Z">
<meta property="article:author" content="Ethan.Tzy">
<meta property="article:tag" content="npm">
<meta property="article:tag" content="包管理工具">
<meta property="article:tag" content="yarn">
<meta property="article:tag" content="pnpm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bu.dusays.com/2022/12/11/63958c4b37912.png"><link rel="shortcut icon" href="https://bu.dusays.com/2022/05/17/6283c38e6368f.ico"><link rel="canonical" href="https://fe32.top/articles/pack1997/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/fortawesome.all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/animate.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/@3.7.1/',
  algolia: {"appId":"KYE9ZA4757","apiKey":"b5a21077c2b61488e5c748ace78c9340","indexName":"blog-tzy1997","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":400},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Ethan.Tzy","link":"链接: ","source":"来源: 唐志远の博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#6f42c1","position":"top-left"},
  source: {
    jQuery: 'https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js',
      css: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/justifiedGallery/3.8.1/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/fancybox/3.5.7/jquery.fancybox.min.js',
      css: 'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/fancybox/3.5.7/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-06-27 22:39:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><style type="text/css">#toggle-sidebar {bottom:70px}</style><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/css/ethan.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/plane_v2.css"><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/right-menu/rightMenu.css"><meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/@3.7.1/atom.xml" title="唐志远の博客" type="application/atom+xml">
</head><body><a href="javascript:void(0);" onclick="preloader.endLoading();" title="点击跳过动画"><div id="loading-box"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div></a><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="onerror=null;src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/archives/"><div class="headline">文章</div><div class="length-num">101</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/@3.7.1/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/@3.7.1/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/@3.7.1/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/@3.7.1/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/gallery/"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/@3.7.1/bangumis/"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page child" href="/@3.7.1/movies/"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page child" href="/@3.7.1/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/@3.7.1/specialEffects/"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page child" href="/@3.7.1/wallpaper/"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/@3.7.1/sponsorWall/"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/comments/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/frdcenter/"><i class="fa-fw fa-fw fas fa-fish-fins"></i><span> 朋友圈</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-coffee"></i><span> 其他</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/demandWall/"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page child" href="/@3.7.1/nav.html"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://bu.dusays.com/2022/12/04/638ca9bf7d3dc.webp')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/@3.7.1/">唐志远の博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/@3.7.1/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-book"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/@3.7.1/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/@3.7.1/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/gallery/"><i class="fa-fw fas fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/@3.7.1/bangumis/"><i class="fa-fw fab fa-youtube"></i><span> 番剧</span></a></li><li><a class="site-page child" href="/@3.7.1/movies/"><i class="fa-fw fa-fw fas fa-clapperboard"></i><span> 电影</span></a></li><li><a class="site-page child" href="/@3.7.1/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/@3.7.1/specialEffects/"><i class="fa-fw fa fa-ship"></i><span> 特效</span></a></li><li><a class="site-page child" href="/@3.7.1/wallpaper/"><i class="fa-fw fa-fw fas fa-images"></i><span> 壁纸</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/@3.7.1/sponsorWall/"><i class="fa-fw fa-fw fas fa-money-check-alt"></i><span> 赞助墙</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/comments/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/frdcenter/"><i class="fa-fw fa-fw fas fa-fish-fins"></i><span> 朋友圈</span></a></div><div class="menus_item"><a class="site-page" href="/@3.7.1/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa-fw fas fa-coffee"></i><span> 其他</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/@3.7.1/demandWall/"><i class="fa-fw fa fa-bug"></i><span> 需求墙</span></a></li><li><a class="site-page child" href="/@3.7.1/nav.html"><i class="fa-fw fa-fw fas fa-infinity"></i><span> 网址收藏</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">包管理工具的演进</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-12-10T08:14:02.000Z" title="发表于 2022-12-10 16:14:02">2022-12-10</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-06-27T14:39:00.662Z" title="更新于 2023-06-27 22:39:00">2023-06-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/@3.7.1/categories/%E5%89%8D%E7%AB%AF%E8%BF%9B%E9%98%B6/">前端进阶</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="包管理工具的演进"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>通过 Node.js 官方内置可以看出，目前前端领域最火的包管理工具主要是 npm（ Node.js 直接内置）、yarn （corepack 内置） 以及 pnpm （corepack 内置）。</p>
<p>因此，本文主要是围绕这三者来阐述包管理工具在迭代演进中提出的一些创新性特性以及其遇到困难是如何解决问题的。</p>
<h2 id="npm"><a href="#npm" class="headerlink" title="npm"></a>npm</h2><h3 id="嵌套结构的依赖"><a href="#嵌套结构的依赖" class="headerlink" title="嵌套结构的依赖"></a>嵌套结构的依赖</h3><p>npm 作为前端领域最早的包管理工具，其早期版本（v1/v2）的工作模式和现在还是有很大的区别，其中最典型的就是 node_modules 的目录管理。</p>
<p>拿以下依赖关系为例：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">Application -&gt; A -&gt; B</span><br><span class="line">            -&gt; C -&gt; B</span><br></pre></td></tr></tbody></table></figure>

<p>则 node_modules 目录结构为：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585a61e92e.png"></div></div>

<p>如上图所示，对于 Application 的依赖，node_modules 的目录结构是层层嵌套的。这样的设计其实很符合直觉，依赖包的安装和目录结构都十分清晰且可预测，但是却带来了两个比较严重问题：</p>
<ol>
<li>依赖包重复安装<br>这个问题在上图中就可以很明显的看出来，B 包被 A 依赖，同时也被 C 所依赖，因此 B 包就分别在 A 和 C 之下分别被安装了一次。这都是没有考虑包版本问题存在的情况下，依赖包都会被重复安装。此种设计结构直接导致了 node_modules 体积过度膨胀，这也是臭名昭著的 node_modules hell 问题。</li>
<li>嵌套层级太深<br>同样如上图所示，应用依赖 A 和 C，而 A 的 node_modules 中又安装了 B，如果 B 也依赖其他包，那么 B 又会存在一个 node_modules 中来存放其他依赖包，如此层层递进。</li>
</ol>
<p>而 Windows 以及一些应用工具无法处理超过 260 个字符的文件和文件夹路径，嵌套层级过深则会导致相应包的路径名很容易就超出了能处理的范围 ，因此会导致一系列问题。比如在想删除相应的依赖包时，系统就无法处理了。（参见：<a target="_blank" rel="noopener" href="https://github.com/nodejs/node-v0.x-archive/issues/6960">Node’s nested node_modules approach is basically incompatible with Windows</a>）</p>
<p>除此之外，npm 还存在着一些问题被人诟病：</p>
<ol>
<li>SemVer 版本管理使得依赖的安装不确定</li>
<li>缓存能力存在问题，且无离线模式</li>
</ol>
<p>因此面对上述问题，特别是 node_modules 的嵌套结构问题，经过社区的反复讨论，npm v3 几乎重写了安装程序，来试图给开发者带来更好的体验。</p>
<h3 id="扁平化"><a href="#扁平化" class="headerlink" title="扁平化"></a>扁平化</h3><p>针对之前 node_moduels 嵌套结构所产生的问题， npm v3 提出的解法就是目录扁平化。同样拿之前的依赖结构为例，npm v2 和 npm v3 的安装目录就完全不一致了。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585a9a0af3.png"></div></div>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585abb3742.png"></div></div>

<p>hoist 机制: npm v3 在处理 A 的依赖 B 时，会将其提升到顶级依赖，然后再处理 C 包，然后发现 C 依赖的 B 包已经被安装了，就不用再重复安装了。</p>
<p>当然上面的举例只是一个理想化的简单 demo，现在考虑一下存在版本不同的情况。</p>
<p>依赖关系变为：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">Application -&gt; A_v1 -&gt; B_v1</span><br><span class="line">            -&gt; C_v1 -&gt; B_v2</span><br></pre></td></tr></tbody></table></figure>

<p>则扁平化的目录结构为：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585add6581.png"></div></div>

<p>如上图所示，在依赖分析过程中，检查到 A v1 依赖了 B v1，因此将 B v1 提升到了顶层。再检查到 C v1 依赖了 B v2 时，发现顶层已经存在了 B v1，因此 B v2 无法提升到顶层，那么只能接着放在 C v1 之下。可以看出，如果出现了同一依赖的不同版本的话，也无法做到完全的扁平化。但是这样的设计在很大程度上确实解决了之前嵌套层级过深的问题。</p>
<h3 id="新的问题"><a href="#新的问题" class="headerlink" title="新的问题"></a>新的问题</h3><p>上面提到了 npm v3 通过扁平化设计 node_modules 来尽量规避同一版本依赖包重复安装的问题和减少层级嵌套过深的问题。但是这个设计也不是十全十美的的，在解决旧有问题的同时也产生了新问题。</p>
<h3 id="phantom-dependencies"><a href="#phantom-dependencies" class="headerlink" title="phantom dependencies"></a>phantom dependencies</h3><p>phantom dependencies 也称幽灵依赖，指的是业务代码中能够引用到 package.json 指定依赖以外的包。拿上面提到过的依赖关系为例：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585add6581.png"></div></div>

<p>package.json 中实际只写明了 Application 依赖 A v1 和 C v1，但是由于 hoist 机制，B v1 被提升到了 node_modules 的第一层目录中，那么依照 node 依赖查找的方式，在我们的业务代码中是可以直接引用 B v1 包的。虽然乍一看也没有比较大的问题，但是 B v1 的版本管理是不在我们的感知之内的。也许某个时期使用了 B v1 的某个方法看起来没有什么问题，等到下次 A 有更新，相应的 A 引用的 B 版本也有了 breaking change 的更新，那么我们在原本代码中使用 B 的方法可能就出现报错。</p>
<h3 id="doppelgangers"><a href="#doppelgangers" class="headerlink" title="doppelgangers"></a>doppelgangers</h3><p>将上面提到的依赖关系中再加入一个 D v1 包，则依赖关系变为：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">Application -&gt; A_v1 -&gt; B_v1</span><br><span class="line">            -&gt; C_v1 -&gt; B_v2</span><br><span class="line">            -&gt; D_v1 -&gt; B_v2</span><br></pre></td></tr></tbody></table></figure>

<p>那么 node_modules 目录结构变为：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585b18be71.png"></div></div>

<p>结果会发现 B v2 又被安装了一份在 D v1 下面。C v1 和 D v1 的依赖都是 B v2 版本，不存在任何差别，但是却依然被重复安装了两遍，这个现象就叫做 doppelgangers，中文名被叫做 “双胞胎陌生人”问题。</p>
<h3 id="被加重的依赖不幂等"><a href="#被加重的依赖不幂等" class="headerlink" title="被加重的依赖不幂等"></a>被加重的依赖不幂等</h3><p>先不考虑 doppelgangers 的现象，可以转过来思考一下 B v2 明明有两个却没有提升到顶层，仍然还是 B v1 在顶层，是什么决定的这个关系呢。</p>
<p><strong>安装顺序很重要！</strong></p>
<p>正常来说，如果是 package.json 里面写好了依赖包，那么 npm install 安装的先后顺序则由依赖包的字母顺序进行排序，那如果是使用 npm install 对每个包进行单独安装，那就看手动的安装顺序了。</p>
<p>如果是先安装的 C v1 ，然后再安装的 A v1，那么提升到顶层的就是 B v2 了。</p>
<p>如果情况再复杂一点，即 Application 又依赖了 E v1 的包：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">Application -&gt; A_v1 -&gt; B_v1</span><br><span class="line">            -&gt; C_v1 -&gt; B_v2</span><br><span class="line">            -&gt; D_v1 -&gt; B_v2</span><br><span class="line">            -&gt; E_v1 -&gt; B_v1</span><br></pre></td></tr></tbody></table></figure>

<p>那么目录结构就会变成</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585b3cb82b.png"></div></div>

<p>之后的迭代过程中， A v1 包被手动升级成 A v2，其依赖项变成了 B v2，那么本地的依赖树结构就变成了：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585b6132b4.png"></div></div>

<p>因为是直接升级的 A 版本，而不是删掉 node_modules 进行重新安装，而由于 E v1 存在，那么 B v1 不会被从 node_modules 中删掉，因此 A v2 的依赖包 B v2 仍然得不到提升，而是依然放在 A v2 之下。</p>
<p>但是，当这版代码上传到服务器上进行部署时，依赖进行重新安装，由于 A v2 的依赖会被最先安装，所以服务器上的依赖树结构则为如下：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/63958632ca353.png"></div></div>

<p>因此可见，本来就因为 SemVer 机制导致的依赖不幂等问题被进一步放大了。</p>
<h3 id="锁文件"><a href="#锁文件" class="headerlink" title="锁文件"></a>锁文件</h3><p>上面提到三个典型问题，其中依赖不幂等的问题在 npm v3 中是提出了相应的解决方法的，那就是 npm-shrinkwrap.json 文件</p>
<p>在 npm v3 版本中，需要手动运行<code>npm shrinkwrap</code>才会生成 npm-shrinkwrap.json 文件，之后每次改动版本依赖，都无法自动更新 npm-shrinkwrap.json 文件，仍然需要手动运行更新，因此这个特性对于开发者来说有一定的成本（开发者可能不知道该特性，或者没有每次及时更新）。</p>
<p>之后受到 yarn.lock 的启发，npm 在 v5 版本中设计了我们现在比较熟悉的 package-lock.json 文件，此时锁文件就是自动生成和更新了。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/63958636082ec.png"></div></div>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395863900442.png"></div></div>

<p>package-lock.json 和 npm-shrinkwrap.json 的作用基本一致，只有一些细微差别：</p>
<ul>
<li>package-lock.json 不会在发布包中出现<br>之前 npm-shrinkwrap.json 允许在发布包中进行版本控制，这样使得子依赖包的版本不容易被共享，从而增加依赖包的体积。</li>
<li>package-lock.json 多了 integrity 参数，用来进行包的 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/Security/Subresource_Integrity">SRI</a> 验证。<br>在本地存在 package-lock.json 文件的情况下，npm 就不需要再去请求查看依赖包的具体信息和满足要求的版本，而是直接通过 lock 文件中内容先去查找文件缓存。若发现没有缓存则直接下载并进行完整性校验，如若无误，则安装。</li>
</ul>
<p>这边简单举例一下完整性校验的 demo，拿 mod-a 包为例，其 integrity 值为：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">sha512-LHSY3BAvHk8CV3O2J2zraDq10+VI1QT1yCTildRW12JSWwFvsnzwLhdOdrJG2gaHHIya7N4GndK+ZFh1bTBjFw==</span><br><span class="line">// 其格式为：(加密函数)-(摘要)</span><br></pre></td></tr></tbody></table></figure>

<p>那么先下载包，包路径为 resolved 值：<a target="_blank" rel="noopener" href="http://bnpm.byted.org/mod-a/-/mod-a-1.0.0.tgz">http://bnpm.byted.org/mod-a/-/mod-a-1.0.0.tgz</a></p>
<p>然后对包进行 SHA512 加密并进行 base64 编码：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395863eed064.png"></div></div>

<p>发现下载下来的依赖包计算出来的 integrity 值和本地的 integrity 值一致，则通过校验。</p>
<h2 id="yarn"><a href="#yarn" class="headerlink" title="yarn"></a>yarn</h2><p>yarn 0.x 版本正式发布的时候，是在 2016 年，也就是 npm v4 还没有发布之前。Yarn 的诞生是由于当时 Facebook 的工程师不满足 npm 所存在的一系列问题，从而开发出来的一个新的包管理工具。由于后发优势，yarn 0.x 版本吸取了 npm v3 优点的同时，也作出了自己的创新：</p>
<ul>
<li>扁平化目录结构</li>
</ul>
<p>yarn 的扁平化结构和 npm 基本类似，但是对重复安装包计算上更加智能一些。</p>
<p>在上面锁文件小节中提到在将 A v1 升级到 A v2 时， npm 安装的时候会出现以下情况：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639585b6132b4.png"></div></div>

<p>而 yarn 则会自动地将 B v1 放在 E v1 下面，而 B v2 则被提升到顶层。</p>
<ul>
<li>锁文件：yarn.lock</li>
</ul>
<p>对比于当时 npm 的 npm-shrinkwrap，yarn.lock 不需要手动生成，而是自动生成和更新。这一点在 npm v5 中被借鉴。</p>
<ul>
<li><p>并行安装，提升安装速度</p>
</li>
<li><p>缓存机制，支持离线安装</p>
</li>
</ul>
<h3 id="workspaces"><a href="#workspaces" class="headerlink" title="workspaces"></a>workspaces</h3><p>之后随着 monorepo 的项目管理方式被逐渐推广，比如 babel 为了管理多包问题开发了 lerna。yarn 也顺势在 v1 版本也增加了相应的功能：yarn workspaces 。</p>
<p>对比早期的 lerna，yarn workspaces 有一个最主要的优势：</p>
<p>lerna bootstrap 是在每个子包内部进行依赖包的单独安装，而 yarn 对依赖包会尽量进行 hoist 处理，也就是在工程的最顶层安装依赖包，这样可以避免共同依赖被重复下载，同时也加快了安装的速度。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/63958643a5789.png"></div></div>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/63958646ed423.png"></div></div>

<p>此外 yarn workspaces 没有封装较多的上层 API，基本上还是依赖于整个 yarn 命令体系，因此使用成本较低。</p>
<blockquote>
<p>当然，后期 lerna 也支持了 hoist 特性，甚至也支持了配合 workspaces 使用，但是最后还是被 babel 官方给放弃并停止维护了。<br>可以阅读 <a target="_blank" rel="noopener" href="https://github.com/babel/babel/discussions/12622">Why babel remove lerna？</a> 来了解 babel 为什么放弃使用 lerna 来管理仓库</p>
</blockquote>
<p>我们可以看到，yarn 虽然在 npm 之上做出了一定的创新和相应的改进，但是在依赖包管理方式上还是借鉴的 npm 的扁平化 node_modules 方式，并没有解决 npm 相应的痛点。也是基于此因素，使得社区部分开发者对其有点失望，pnpm 应运而生。</p>
<!-- https://www.lofter.com/ -->

<h2 id="pnpm"><a href="#pnpm" class="headerlink" title="pnpm"></a>pnpm</h2><p>pnpm 在依赖包管理方式上完全舍弃了 npm 的那一套，而是巧妙利用 symbol link 和 hard link 做出了自己的创新。</p>
<h3 id="symbol-link"><a href="#symbol-link" class="headerlink" title="symbol link"></a>symbol link</h3><p>上面提到过 npm 在扁平化 node_modules 之后带来了新的问题，而 pnpm 利用符号链接的方式重新设计了 node_modules 的结构来处理扁平化带来的问题。</p>
<p>复用之前提到过的依赖关系：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">Application -&gt; A_v1 -&gt; B_v1</span><br><span class="line">            -&gt; C_v1 -&gt; B_v2</span><br><span class="line">            -&gt; D_v1 -&gt; B_v2</span><br></pre></td></tr></tbody></table></figure>

<p>那么目录结构则为：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586490c11e.png"></div></div>

<p>通过上图可以看出，pnpm 的依赖树结构和之前 npm 或者 yarn 的扁平化完全不同：</p>
<ol>
<li>只有应用直接依赖的 A v1、C v1 以及 D v1 包在 node_modules 顶层中，而依赖的依赖，比如 B v1 和 B v2 都不在。那么如果在项目中直接引用 B 就无法找到相应的依赖包，直接报错。因此这点完全避免了 phantom dependencies 的发生。</li>
<li>顶层 node_module 中的 A v1、C v1 以及 D v1 包都是源文件依赖包的 symbol link，源文件依赖包还有其相应的子依赖包都放在了 .pnpm 目录中。</li>
<li>虽然表面上看起来 C v1 的依赖 B v2 以及 D v1 的依赖 B v2 也被重复的安装了两次，但是这两个 B v2 都是源文件 B v2 的 symbol link，因此这个设计也避免了 doppelgangers 的问题。</li>
</ol>
<h3 id="hard-link"><a href="#hard-link" class="headerlink" title="hard link"></a>hard link</h3><p>pnpm 在安装的过程中，会在全局的 store 目录中去存储依赖包，然后在项目对应的 node_modules 中创建相应的硬链接。由于不能对目录进行 hard link，因此不像 npm 一样缓存的是压缩包，pnpm 是将依赖包的每个文件都缓存到 store 中，然后创建相应文件的硬链。</p>
<p>我们可以简单看一下 demo 实例，下图为依赖关系和相应的 lock 文件：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395868468413.png"></div></div>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586874d668.png"></div></div>

<p>通过看 pnpm 源码可以知道， pnpm 是利用 ssri 这个包来将 integrity 进行 base64 转码来决定缓存目录的。</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586899414c.png"></div></div>

<p>那么去到 store 目录下</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395868b355e7.png"></div></div>


<p>而 mod-a 文件的转码为<br><code>2c7498dc102f1e4f025773b6276ceb683ab5d3e548d504f5c824e295d456d762525b016fb27cf02e174e76b246da06871c8c9aecde069dd2be6458756d306317</code></p>
<p>因此进入 2c 目录下面，就可以发现 mod-a 包的信息了</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395868e8e77d.png"></div></div>

<p>将 json 标准格式化一下</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395869155cdd.png"></div></div>

<p>可以看出 mod-a 依赖包中只包含了 3 个文件，拿 README.md 文件的 integrity 再同样处理一次：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586944ef83.png"></div></div>

<p>拿到编码找目录</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/63958696ace9a.png"></div></div>

<p>接着进入项目依赖的 mod-a 的真正源文件处</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586c7ad9f3.png"></div></div>

<p>那么现在就可以证明，项目依赖包的源文件就是 store 目录下的 hard link 了。</p>
<p>因此如果要下载的依赖包已经在 store 中存在了，就不需要重新下载，而是直接创建相应的硬链接即可，很大程度的节省了下载时间。</p>
<p>此外，在本地往往会有多个工程在开发，而每个工程的依赖项大多时候都是大同小异的，因此统一在 store 中管理存储并硬链出去的方式允许跨项目共享同一版本的依赖，从而也节省了大量的存储空间。</p>
<h3 id="why-hard-link"><a href="#why-hard-link" class="headerlink" title="why hard link"></a>why hard link</h3><p>有一点值得提出来思考一下，为什么 pnpm 既要用 symbol link，又要使用 hard link，为什么不能全部使用一种呢。</p>
<p>为了弄清楚这个问题，同时加深对此模式的理解，我们需要明白 symbol link 和 hard link 对 node 寻包的影响。</p>
<p>demo 如下</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586c9c093f.png"></div></div>

<p>接着尝试运行</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586ce2c033.png"></div></div>

<p>发现运行 symbol link 的文件会失败，报找不到 lodash 包，而运行 hard link 的文件则正常。</p>
<p>接着在 source 中也创建一个 node_modules，然后再次运行</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586d016e6f.png"></div></div>

<p>结果发现这次 symbol link 和 hard link 都运行正常，证明两者都找到了相应的依赖包。</p>
<p>从这个 demo 可以看出，symbol link 的文件会回到源文件的目录去寻找依赖包，而 hard link 的文件则会在文件本来的目录下去寻找依赖包。</p>
<p>其实回过头来发现，.pnpm 目录的设计也正是利用 symbol link 的这一点去巧妙的与 node module resolution 机制结合才做到了规避 phantom dependencies 现象。而如果全部使用 symbol link 的话，那就会都去 store 中寻找子依赖了，这样就很难做到区分同个包的不同版本。</p>
<h3 id="缺陷"><a href="#缺陷" class="headerlink" title="缺陷"></a>缺陷</h3><p>很难有完美的设计，pnpm 解决了 npm 扁平化依赖带来的硬伤，但是同时也存在着一些小的问题：</p>
<ol>
<li>兼容性问题，因为整体设计上使用了 symbol link 和 hard link， 如果所处的环境对其支持存在问题 或者某些 npm 包中写死了引用路径，就会导致使用出错。</li>
<li>因为依赖包会在 store 中全局维护，那么如果在开发中有调试 npm 的情况，修改 npm 包会导致所有工程引用的该包都发生修改。</li>
</ol>
<h2 id="yarn-berry"><a href="#yarn-berry" class="headerlink" title="yarn berry"></a>yarn berry</h2><p>上面提到 yarn 在正式发布的时候，虽然在 npm 之上做了一定的改进，但是在依赖包管理上还是借鉴了 npm 扁平化模式，没有解决依赖引用的核心问题。之后 pnpm 大胆创新的想法被提出，在设计思想层面，yarn 明显就处于了落后位置。在内卷的环境之下，yarn pnp 模式很快就被提出。之后，yarn 放弃了 yarn v1 版本的迭代，将 yarn v1 定性为 yarn classic，从而 yarn berry 诞生。</p>
<h3 id="pnp-模式"><a href="#pnp-模式" class="headerlink" title="pnp 模式"></a>pnp 模式</h3><div class="tzy-post">

<p>yarn 认为目前包管理工具出现的各种问题很大程度上来自于 node_modules 本身：<strong>无论怎么样利用缓存，或者使用什么样的思路以及目录结构来设计 node_modules，只要你生成它，那么就需要知道 node_modules 要包含的内容并且执行繁重的 I/O 操作。</strong></p>
</div>

<p>而为什么之前包管理工具一定要生成 node_modules 的依赖包呢，原因在于 node module resolution 的机制就是如此，即 node 会一层一层的依照目录层级顺序去 node_modules 中去寻找相应的依赖。</p>
<p>但是在安装依赖的过程中，包管理工具将会去获取并梳理项目依赖树的所有信息，那么在已知了项目依赖信息之后，为什么还要依靠 node 再去寻找一次依赖包呢，这个就是 pnp 特性要解决的问题。</p>
<p>在 pnp 模式下，安装项目依赖后根目录下将不会出现 node_modules 文件夹了，相应代替的则是 .pnp.cjs 文件。</p>
<p>使用 yarn berry 安装的项目依赖关系如下：</p>
<figure class="highlight plain"><table><tbody><tr><td class="code"><pre><span class="line">Application  -&gt; mod-a.v1 -&gt; mod-b.v1</span><br><span class="line">             -&gt; mod-c.v1 -&gt; mod-b.v2</span><br><span class="line">             -&gt; mod-d.v1 -&gt; mod-b.v1</span><br></pre></td></tr></tbody></table></figure>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586d25d91a.png"></div></div>

<p>其中 .yarn/cache 为所有依赖包的 zip 文件</p>
<p>在 .pnp.cjs 文件中主要做了两件事情：</p>
<ul>
<li>维护依赖包的版本、依赖包之间相互的依赖关系以及依赖包 zip 存储的位置</li>
<li>对 node 的文件解析模块打上 monkey patch，使得代码在引入依赖的时候不走原本的 node_modules 解析那一套，而是直接寻找依赖包所在的位置。</li>
</ul>
<p>可以写一个 demo 来简单模拟一下 .pnp.cjs 的作用：</p>
<p>依赖包文件</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586d3c693b.png"></div></div>

<p>执行文件</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586d7c961f.png"></div></div>

<p>如果正常执行 index.js，那么一定会报错找不到 math 模块：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639586dacc151.png"></div></div>

<p>那么在此情况下，加上一个 monkey patch：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395871b71662.png"></div></div>

<p>再次运行</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395871d86482.png"></div></div>

<p>此时会发现在打了补丁之后，代码就顺利的找到了依赖文件了。当然 .pnp.cjs 做的事情要比 demo 复杂的多，比如各种路径解析的 patch 以及兼容，再比如利用 zlib 来解压依赖压缩包。总之，pnp 模式自己解析模块路径的方式有着诸多优势：</p>
<ul>
<li>完全解决了 doppelgangers 和 phantom dependencies 等问题</li>
<li>减少了 I/O 操作，yarn 只需要生成 .pnp.cjs 文件和依赖包的 cache 文件，而不是像以前一样成千上万个文件，主要的瓶颈由原来的磁盘性能真正变成了依赖的数量，使得安装变得更加高效且稳定。</li>
<li>代码启动的速度更快，因为不需要使用 node 路径解析来遍历整个项目文件系统</li>
<li>如果将 cache 的 zip 文件纳入 git 管理，那么可以实现 zero-installs 能力</li>
</ul>
<p>当然，相应的缺点也很明显，即完全脱离了 node_modules resolution 机制，步子迈得太大，因此在兼容性上有一定的问题，这个也就是 yarn berry 在刚刚推出之后不怎么受欢迎的原因。但是在后续的迭代中， yarn 在兼容性上做了很多的工作，现在主流的一些工具，比如 webpack、babel、esbuild 等都已支持 pnp 模式。</p>
<h3 id="插件化"><a href="#插件化" class="headerlink" title="插件化"></a>插件化</h3><p>除了 pnp 模式以外, yarn berry 还提供了一种比较新颖的特性：插件扩展。从 yarn v1 到 yarn v2，yarn 将代码架构改成了支持插件化扩展的模式。通过插件扩展，我们可以实现很多增强性功能，比如为 yarn 添加新的命令、在生命周期钩子上做一些定制化的事情等。</p>
<p>拿一个比较有意思的官方插件<code>@yarnpkg/plugin-typescript</code>举例，通过在<code>afterWorkspaceDependencyAddition</code>生命周期钩子里面去查询安装的包是否存在有相应的 @types 的包，如果有并且没有被安装，那么就会顺便安装一下。</p>
<p>实验一下：</p>
<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/639587206c447.png"></div></div>

<div class="img-wrap"><div class="img-bg"><img class="img" src= "https://bu.dusays.com/2022/01/14/1ff50a00bd75c.gif" data-lazy-src="https://bu.dusays.com/2022/12/11/6395872295437.png"></div></div>

<p>发现在安装 lodash 的时候，@types/lodash 的包也同样被安装下载了。</p>
<p>Yarn 除了提供的官方插件之外，同样也提供了 API 来鼓励用户来贡献第三方插件，可以看出从灵活性，定制化方面，yarn 插件化的设计目前是走在其他包管理工具的前面。</p>
<h2 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h2><p>其实关于 npm、yarn 以及 pnpm 的迭代演进远远不只是做了上面提到的工作，比如：</p>
<ul>
<li>npm 在 v5.x 版本中增加了 npx 命令，yarn v2 紧跟其后的 yarn dlx 命令，pnpm v6.x 也新增了 pnpm dlx 命令 以及在 v7 版本又增加了 pnpx</li>
<li>pnpm 在 v5.x 版本中也支持了 pnp 模式</li>
<li>yarn 在 v3.1 版本中支持了 pnpm 模式的 nodeLinker</li>
<li>yarn 在 v3.1 版本中支持了 optionalDependencies 依赖分发</li>
<li>……</li>
</ul>
<p>通过以上发现，包管理工具在自我创新的同时都在互相学习对方的优点，尤其是 pnpm 和 yarn，为 JavaScript 社区的发展注入了活力。而我们通过了解学习它们的演进历程，可以加深对依赖包管理的理解，从而在工程开发中更好的选型以及解决相应的问题。</p>
<blockquote>
<p>原文链接：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/beP1bxgbTT1Z91KS3svDvw">字节前端 ByteFE - 包管理工具的演进</a></p>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://fe32.top">Ethan.Tzy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://fe32.top/articles/pack1997/">https://fe32.top/articles/pack1997/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://fe32.top" target="_blank">唐志远の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/@3.7.1/tags/npm/">npm</a><a class="post-meta__tags" href="/@3.7.1/tags/%E5%8C%85%E7%AE%A1%E7%90%86%E5%B7%A5%E5%85%B7/">包管理工具</a><a class="post-meta__tags" href="/@3.7.1/tags/yarn/">yarn</a><a class="post-meta__tags" href="/@3.7.1/tags/pnpm/">pnpm</a></div><div class="post_share"><div class="social-share" data-image="https://bu.dusays.com/2022/12/11/63958c4b37912.png" data-sites="facebook,twitter,google,wechat,weibo,qq"></div><link rel="stylesheet" href="https://npm.elemecdn.com/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://bu.dusays.com/2022/05/17/6283c3f127558.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://bu.dusays.com/2022/05/17/6283c3ee6d872.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/@3.7.1/articles/hexo1617/"><img class="prev-cover" data-lazy-src="https://bu.dusays.com/2022/12/11/6395eec4c51ed.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Hexo + Butterfly 自定义页脚</div></div></a></div><div class="next-post pull-right"><a href="/@3.7.1/articles/blog9527/"><img class="next-cover" data-lazy-src="https://bu.dusays.com/2022/12/13/63987cfb1d701.png" onerror="onerror=null;src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">时光飞逝，博客两周年啦</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/@3.7.1/articles/9r95s1wt/" title="Nvm,npm与nrm"><img class="cover" data-lazy-src="https://bu.dusays.com/2022/05/02/626eaea70e682.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-30</div><div class="title">Nvm,npm与nrm</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" onerror="this.onerror=null;this.src='https://bu.dusays.com/2021/03/27/0106da541a922.gif'" alt="avatar"/><div class="author-info__name">Ethan.Tzy</div><div class="author-info__description">2023年的理想开始实现了吗？</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/@3.7.1/archives/"><div class="headline">文章</div><div class="length-num">101</div></a></div><div class="card-info-data-item is-center"><a href="/@3.7.1/tags/"><div class="headline">标签</div><div class="length-num">73</div></a></div><div class="card-info-data-item is-center"><a href="/@3.7.1/categories/"><div class="headline">分类</div><div class="length-num">20</div></a></div></div><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2938526863&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://bu.dusays.com/2022/05/17/6283c39fcfc2f.png" target="_blank" title="Wechat"><i class="fab fa-weixin"></i></a><a class="social-icon" href="mailto:ethan4116@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://github.com/tzy13755126023" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/@3.7.1/atom.xml" target="_blank" title="Rss"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><div style='text-indent:2em'>本站只保留入口，即将不再更新内容，请切换成回最新版本。</div><div id="qq-btn"><a id="a-qun" href="https://fe32.top/" target="_blank">回最新版本 ✨</a></div><div id="qq-btn" style="margin-top:10px"><a id="a-qun" href="https://qm.qq.com/cgi-bin/qm/qr?k=IqfyAyFpCIMln6xPXkjkI_gzF8zx29zK&jump_from=webapi&authKey=jcME5f+e8XES0vAaUTAaI24tsgUMdoIZ0oGwAOoHNpK1HSWdcI9zmSlWVdfw/ax+" target="_blank">加入QQ群 ✨</a></div></div></div><div class="card-widget tzy-right-widget" id="card-wechat"><div id="flip-wrapper"><div id="flip-content"><div class="face"></div><div class="back face"></div></div></div></div><div class="xpand" style="height:200px;"><canvas class="illo" width="800" height="800" style="max-width: 200px; max-height: 200px; touch-action: none; width: 640px; height: 640px;"></canvas></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#npm"><span class="toc-number">2.</span> <span class="toc-text">npm</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E7%BB%93%E6%9E%84%E7%9A%84%E4%BE%9D%E8%B5%96"><span class="toc-number">2.1.</span> <span class="toc-text">嵌套结构的依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%81%E5%B9%B3%E5%8C%96"><span class="toc-number">2.2.</span> <span class="toc-text">扁平化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B0%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">2.3.</span> <span class="toc-text">新的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#phantom-dependencies"><span class="toc-number">2.4.</span> <span class="toc-text">phantom dependencies</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#doppelgangers"><span class="toc-number">2.5.</span> <span class="toc-text">doppelgangers</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A2%AB%E5%8A%A0%E9%87%8D%E7%9A%84%E4%BE%9D%E8%B5%96%E4%B8%8D%E5%B9%82%E7%AD%89"><span class="toc-number">2.6.</span> <span class="toc-text">被加重的依赖不幂等</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%94%81%E6%96%87%E4%BB%B6"><span class="toc-number">2.7.</span> <span class="toc-text">锁文件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#yarn"><span class="toc-number">3.</span> <span class="toc-text">yarn</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#workspaces"><span class="toc-number">3.1.</span> <span class="toc-text">workspaces</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#pnpm"><span class="toc-number">4.</span> <span class="toc-text">pnpm</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#symbol-link"><span class="toc-number">4.1.</span> <span class="toc-text">symbol link</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#hard-link"><span class="toc-number">4.2.</span> <span class="toc-text">hard link</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#why-hard-link"><span class="toc-number">4.3.</span> <span class="toc-text">why hard link</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%BA%E9%99%B7"><span class="toc-number">4.4.</span> <span class="toc-text">缺陷</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#yarn-berry"><span class="toc-number">5.</span> <span class="toc-text">yarn berry</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#pnp-%E6%A8%A1%E5%BC%8F"><span class="toc-number">5.1.</span> <span class="toc-text">pnp 模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%92%E4%BB%B6%E5%8C%96"><span class="toc-number">5.2.</span> <span class="toc-text">插件化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9C%80%E5%90%8E"><span class="toc-number">6.</span> <span class="toc-text">最后</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/joy10001/" title="被发现了，这些吊炸天的摸鱼网站！"><img data-lazy-src="https://bu.dusays.com/2023/06/18/648f1359dc90f.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="被发现了，这些吊炸天的摸鱼网站！"/></a><div class="content"><a class="title" href="/@3.7.1/articles/joy10001/" title="被发现了，这些吊炸天的摸鱼网站！">被发现了，这些吊炸天的摸鱼网站！</a><time datetime="2023-06-18T16:40:07.000Z" title="发表于 2023-06-19 00:40:07">2023-06-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/vue20002/" title="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题"><img data-lazy-src="https://bu.dusays.com/2023/06/18/648ed3f987511.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题"/></a><div class="content"><a class="title" href="/@3.7.1/articles/vue20002/" title="解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题">解决 Vue 中使用 Echarts 出现 There Is a Chart Instance Already Initialized on the Dom 的警告问题</a><time datetime="2023-06-18T16:20:32.000Z" title="发表于 2023-06-19 00:20:32">2023-06-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/hexo1619/" title="如何新窗口打开导航链接？"><img data-lazy-src="https://bu.dusays.com/2023/06/04/647c9bb365e09.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="如何新窗口打开导航链接？"/></a><div class="content"><a class="title" href="/@3.7.1/articles/hexo1619/" title="如何新窗口打开导航链接？">如何新窗口打开导航链接？</a><time datetime="2023-06-04T13:53:07.000Z" title="发表于 2023-06-04 21:53:07">2023-06-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/ts30001/" title="一文读懂TS的(.d.ts)文件"><img data-lazy-src="https://bu.dusays.com/2023/04/29/644d384035bca.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="一文读懂TS的(.d.ts)文件"/></a><div class="content"><a class="title" href="/@3.7.1/articles/ts30001/" title="一文读懂TS的(.d.ts)文件">一文读懂TS的(.d.ts)文件</a><time datetime="2023-04-30T14:28:06.000Z" title="发表于 2023-04-30 22:28:06">2023-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/@3.7.1/articles/vue20001/" title="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法"><img data-lazy-src="https://bu.dusays.com/2023/04/29/644d249bc9001.png" onerror="this.onerror=null;this.src='https://bu.dusays.com/2022/01/14/82eed74cbb1e0.jpg'" alt="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法"/></a><div class="content"><a class="title" href="/@3.7.1/articles/vue20001/" title="Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法">Property 'Xxx' Does Not Exist on Type 'AxiosResponse&lt;any, Any&gt;' 的解决办法</a><time datetime="2023-04-30T12:34:18.000Z" title="发表于 2023-04-30 20:34:18">2023-04-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://bu.dusays.com/2022/12/04/638ca9bf7d3dc.webp')"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">公益广告</p><div class="bg-ad"><div>国家反诈中心是国务院打击治理电信网络新型违法犯罪工作部际联席会议合成作战平台，集资源整合、情报研判、侦查指挥为一体，在打击、防范、治理电信网络诈骗等新型违法犯罪中发挥着重要作用。</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://www.hack-gov.com.cn/posts/21480.html">下载（国家反诈中心） APP</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">修仙导航</p><ul class="ft-links"><li><a target="_blank" rel="noopener" href="https://tzy1997.com/articles/hexo1600/">建站指南</a><a target="_blank" rel="noopener" href="https://tzy1997.com/nav.html">网址导航</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/sponsorWall/">来杯咖啡</a><a target="_blank" rel="noopener" href="https://tzy1997.com/comments/">留点什么</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/about/">关于博主</a><a target="_blank" rel="noopener" href="https://tzy1997.com/archives/">文章归档</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/categories/">文章分类</a><a target="_blank" rel="noopener" href="https://tzy1997.com/tags/">文章标签</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/gallery/">我的相册</a><a target="_blank" rel="noopener" href="https://tzy1997.com/bangumis/">我的追番</a></li><li><a target="_blank" rel="noopener" href="https://tzy1997.com/specialEffects/">一些特效</a><a target="_blank" rel="noopener" href="https://tzy1997.com/wallpaper/">一些壁纸</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链</p><div class="ft-img-group"><div class="img-group-item"><a target="_blank" rel="noopener" href="https://tzy1997.com/"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://blog.zhheo.com/"><img src="https://npm.elemecdn.com/guli-heo/img/avatar2.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.thyuu.com/"><img src="https://npm.elemecdn.com/imgscdn/img/202111191951780.JPG" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://dusays.com/"><img src="https://cdn.dusays.com/avatar.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://akilar.top/"><img src="https://npm.elemecdn.com/akilar-candyassets/image/siteicon/favicon.png" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.fomal.cc/"><img src="https://bu.dusays.com/2022/11/06/6367af8667f0e.webp" alt=""/></a></div><div class="img-group-item"><a target="_blank" rel="noopener" href="https://www.startly.cn/"><img src="https://bu.dusays.com/2023/04/15/643a99cb740a4.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:btf.snackbarShow(&quot;预留友链位~~&quot;)"><img src="https://bu.dusays.com/2022/05/02/626f92e193879.jpg" alt=""/></a></div></div></div></div><div class="copyright">&copy;2020 - 2023  <i id="heartbeat" class="fa fas fa-heartbeat"></i> Ethan.Tzy</div><div class="footer_custom_text">I wish you to become your own sun, no need to rely on who's light.✨✨✨<p><a target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a>&nbsp;<a target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://icp.gov.moe/?keyword=20220686" title="本站已加入萌ICP豪华套餐，萌ICP备20220686号"><img src="https://img.shields.io/badge/%E8%90%8CICP%E5%A4%87-20220686-fe1384?style-flat&amp;logo="></a>&nbsp;<a target="_blank" href="https://vercel.com/"><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="在线聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuPlugin"><div class="rightMenu-item" id="menu-copytext"><i class="fa-solid fa-copy"></i><span>复制文本</span></div><div class="rightMenu-item" id="menu-newwindow"><i class="fa-solid fa-window-restore"></i><span>新窗口打开</span></div><div class="rightMenu-item" id="menu-copylink"><i class="fa-solid fa-copy"></i><span>复制链接地址</span></div><div class="rightMenu-item" id="menu-copyimg"><i class="fa-solid fa-copy"></i><span>复制图片</span></div><div class="rightMenu-item" id="menu-downloadimg"><i class="fa-solid fa-download"></i><span>下载图片</span></div><div class="rightMenu-item" id="menu-search"><i class="fa-solid fa-magnifying-glass"></i><span>站内搜索</span></div><div class="rightMenu-item" id="menu-searchBaidu"><i class="fa-solid fa-magnifying-glass"></i><span>百度搜索</span></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><div class="rightMenu-item" id="menu-radompage"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></div><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a><a class="rightMenu-item" id="menu-goto-comment" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item menu-link" href="/sponsorWall/"><i class="fa-solid fa-money-check-alt"></i><span>赞助墙</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-readmode"><i class="fa-solid fa-book-open"></i><span>阅读模式</span></div><div class="rightMenu-item" id="menu-print"><i class="fa-solid fa-print fa-fw"></i><span>打印页面</span></div><div class="rightMenu-item" id="menu-copy"><i class="fa-solid fa-share"></i><span>分享本页</span></div></div></div><div id="rightmenu-mask"></div><div id="myscoll"></div><div><script src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script src="/@3.7.1/"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/utils.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/main.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/tw_cn.js"></script><script src="https://npm.elemecdn.com/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/search/algolia.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);</script><div class="js-pjax"><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo.fe32.top/',
      region: '',
      onCommentLoaded: function () {
        //- const ele = document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)')
      }
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo.fe32.top/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://fastly.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo.fe32.top/',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://fastly.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><div class="pjax-reload"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '1s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('site-card');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInY');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '100ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script><script async="async">var arr = document.getElementsByClassName('github-badge');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__flipInX');
    arr[i].setAttribute('data-wow-duration', '3s');
    arr[i].setAttribute('data-wow-delay', '100ms');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer="defer" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/wow.min.js"></script><script defer="defer" src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/wow_init.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/cat.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/issues.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople1.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/zdog.dist.js"></script><script defer data-pjax src="https://npm.elemecdn.com/ethan4116-blog/lib/js/other/two-people/twopeople.js"></script><canvas id="universe"></canvas><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/universe.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/@3.7.1/js/ethan_tzy.js"></script><script defer src="https://npm.elemecdn.com/ethan4116-blog/lib/right-menu/rightMenu@3.7.1.js"></script><script async src="//at.alicdn.com/t/font_2315348_g8vs01iykv.js"></script><script async src="https://www.googletagmanager.com/gtag/js?id=G-92YZLM7C2B"></script><script> window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', 'G-92YZLM7C2B');</script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9697737937582017" crossorigin="anonymous"></script><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "https://hm.baidu.com/hm.js?bbcbaf179f87d03d28c3ba72c79a5640";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s);})();</script><script>!function(p){"use strict";!function(t){var s=window,e=document,i=p,c="".concat("https:"===e.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=e.createElement("script"),r=e.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",i.d=n;var o=function(){s.LA.ids.push(i)};s.LA?s.LA.ids&&o():(s.LA=p,s.LA.ids=[],o()),r.parentNode.insertBefore(n,r)}()}({id:"Jo9JJAc5cBaxwwnJ",ck:"Jo9JJAc5cBaxwwnJ"});</script><script src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://npm.elemecdn.com/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script>window.$crisp = [];
window.CRISP_WEBSITE_ID = "58b8ce9e-19e0-46ff-8e8d-6ee1b1b25c45";
(function () {
  d = document;
  s = d.createElement("script");
  s.src = "https://client.crisp.chat/l.js";
  s.async = 1;
  d.getElementsByTagName("head")[0].appendChild(s);
})();
$crisp.push(["safe", true])

if (true) {
  $crisp.push(["do", "chat:hide"])
  $crisp.push(["on", "chat:closed", function() {
    $crisp.push(["do", "chat:hide"])
  }])
  var chatBtnFn = () => {
    var chatBtn = document.getElementById("chat_btn")
    chatBtn.addEventListener("click", function(){
      $crisp.push(["do", "chat:show"])
      $crisp.push(["do", "chat:open"])

    });
  }
  chatBtnFn()
} else {
  if (false) {
    function chatBtnHide () {
      $crisp.push(["do", "chat:hide"])
    }
    function chatBtnShow () {
      $crisp.push(["do", "chat:show"])
    }
  }
}</script><link rel="stylesheet" href="https://npm.elemecdn.com/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://npm.elemecdn.com/aplayer/dist/APlayer.min.js"></script><script src="https://npm.elemecdn.com/ethan4116-blog/lib/js/theme/meting.min.js"></script><script src="https://npm.elemecdn.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener toc scroll 
  window.removeEventListener('scroll', window.tocScrollFn)

  typeof preloader === 'object' && preloader.initLoading()

  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  //- document.querySelectorAll('script[data-pjax]').forEach(item => {
  
  document.querySelectorAll('script[data-pjax], .pjax-reload script').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})


//- document.addEventListener('pjax:send', function () {
//-   typeof preloader === 'object' && preloader.initLoading()
  
//-   if (window.aplayers) {
//-     for (let i = 0; i < window.aplayers.length; i++) {
//-       if (!window.aplayers[i].options.fixed) {
//-         window.aplayers[i].destroy()
//-       }
//-     }
//-   }

//-   typeof typed === 'object' && typed.destroy()

//-   //reset readmode
//-   const $bodyClassList = document.body.classList
//-   $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

//- })

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    if (false) {
      location.hash && e.request.responseURL !== location.href ? pjax.loadUrl(location.href) : pjax.loadUrl('/404.html')
      return
    }
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>